package org.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.chen.common.ChatHistory;
import org.chen.common.UserQuery;
import org.chen.common.UserWithChat;
import org.chen.dto.FindPasswordDto;
import org.chen.dto.LoginDto;
import org.chen.dto.RegisterDto;
import org.chen.dto.UpdatePasswordDto;
import org.chen.exception.CustomException;
import org.chen.mapper.ChatHistoryMapper;
import org.chen.mapper.UserQueryMapper;
import org.chen.mapper.UserWithChatMapper;
import org.chen.result.CommonResponse;
import org.chen.result.FindPasswordResponse;
import org.chen.result.LoginResponse;
import org.chen.result.RegisterResponse;
import org.chen.service.UserWithChatService;
import org.chen.service_enum.ErrorCode;
import org.chen.utils.Base62;
import org.chen.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

@Service
public class UserWithChatServiceImpl extends ServiceImpl<UserWithChatMapper, UserWithChat> implements UserWithChatService {

    @Autowired
    private UserWithChatMapper userWithChatMapper;

    @Autowired
    private ChatHistoryMapper chatHistoryMapper;

    @Autowired
    private UserQueryMapper userQueryMapper;

    @Override
    public RegisterResponse register(RegisterDto registerDto) {
        if (registerDto == null){
            throw new CustomException(400,"参数错误");
        }

        RegisterResponse registerResponse = new RegisterResponse();
        boolean name = userWithChatMapper.exists(new QueryWrapper<UserWithChat>().eq("name", registerDto.getName()));
        if (name){
            return registerResponse.setNameExits(true);
        }

        boolean email = userWithChatMapper.exists(new QueryWrapper<UserWithChat>().eq("email", registerDto.getEmail()));
        if (email){
            return registerResponse.setEmailExits(true);
        }

        UserWithChat userWithChat = new UserWithChat();
        userWithChat.setEmail(registerDto.getEmail());
        userWithChat.setName(registerDto.getName());
        userWithChat.setDef(false);
        userWithChat.setPassword(MD5Utils.stringMD5(registerDto.getPassword()));
        int insert = userWithChatMapper.insert(userWithChat);
        if (insert > 0){
            String uid = Base62.encode(Long.parseLong(userWithChat.getObjectId()));
            userWithChat.setUid(uid);
            userWithChatMapper.updateById(userWithChat);
            return registerResponse.setSuccess(true);
        }else {
            return registerResponse.setSuccess(false);
        }
    }

    @Override
    public LoginResponse login(LoginDto loginDto) {
        if (loginDto == null){
            throw new CustomException(400,"参数错误");
        }
        LoginResponse loginResponse = new LoginResponse();
        if (loginDto.getType().equals("Google")){
            UserWithChat email = userWithChatMapper.selectOne(new QueryWrapper<UserWithChat>().eq("email", loginDto.getEmail()));
            if (email == null){
                UserWithChat userWithChat = new UserWithChat();
                userWithChat.setEmail(loginDto.getEmail());
                userWithChat.setName(loginDto.getUserName());
                userWithChat.setPassword(MD5Utils.stringMD5(loginDto.getEmail()));
                int insert = userWithChatMapper.insert(userWithChat);
                if (insert > 0){
                    String uid = Base62.encode(Long.parseLong(userWithChat.getObjectId()));
                    userWithChat.setUid(uid);
                    userWithChatMapper.updateById(userWithChat);
                    userWithChat.setPassword("");
                    return loginResponse.setUserWithChat(userWithChat);
                }else {
                    return loginResponse.setSuccess(false);
                }
            }else {
                email.setLoginTime(LocalDateTime.now());
                userWithChatMapper.updateById(email);
                email.setPassword("");
                return loginResponse.setUserWithChat(email);
            }
        }else {
            UserWithChat userWithChat = userWithChatMapper.selectOne(new QueryWrapper<UserWithChat>().eq("email", loginDto.getUserName()).eq("password", MD5Utils.stringMD5(loginDto.getPassword())));
            if (userWithChat == null){
                return loginResponse.setSuccess(false);
            }
            userWithChat.setLoginTime(LocalDateTime.now());
            userWithChatMapper.updateById(userWithChat);
            userWithChat.setPassword("");
            return loginResponse.setUserWithChat(userWithChat);
        }

    }

    @Override
    public CommonResponse delete(String objectId) {
        if (objectId == null){
            throw new CustomException(400,"参数错误");
        }
        int i = userWithChatMapper.deleteById(objectId);
        if (i > 0){
            chatHistoryMapper.delete(new QueryWrapper<ChatHistory>().eq("userId",objectId));
            userQueryMapper.delete(new QueryWrapper<UserQuery>().eq("userId",objectId));
        }else {
            return CommonResponse.error(ErrorCode.DELETE_USER.getCode(),ErrorCode.DELETE_USER.getMessage(),ErrorCode.DELETE_USER.getMessage());
        }
        return CommonResponse.success();
    }

    @Override
    public CommonResponse updateUser(UserWithChat user) {
        if (user == null){
            throw new CustomException(400,"参数错误");
        }
        UserWithChat userWithChatByPhone = userWithChatMapper.selectOne(new QueryWrapper<UserWithChat>().eq("phone", user.getPhone()));
        UserWithChat userWithChatByName = userWithChatMapper.selectOne(new QueryWrapper<UserWithChat>().eq("name", user.getName()));
        if (userWithChatByPhone != null && !Objects.equals(userWithChatByPhone.getObjectId(), userWithChatByName.getObjectId())) {
            return CommonResponse.error(ErrorCode.EXIST.getCode(),ErrorCode.EXIST.getMessage(),ErrorCode.EXIST.getMessage());
        }

        UserWithChat userWithChat = userWithChatMapper.selectById(user.getObjectId());
        if (userWithChat == null){
            return CommonResponse.error(ErrorCode.EXITS.getCode(),ErrorCode.EXITS.getMessage(),ErrorCode.EXITS.getMessage());
        }

        userWithChat.setRelName(user.getName());
        userWithChat.setEmail(user.getEmail());
        userWithChat.setPhone(user.getPhone());
        userWithChat.setGenderId(user.getGenderId());
        userWithChat.setRelName(user.getRelName());
        int i = userWithChatMapper.updateById(userWithChat);
        if (i > 0){
            return CommonResponse.success();
        }else {
            return CommonResponse.error(ErrorCode.UPDATE_FAILED.getCode(),ErrorCode.UPDATE_FAILED.getMessage(),ErrorCode.UPDATE_FAILED.getMessage());
        }

    }

    @Override
    public CommonResponse updatePassword(UpdatePasswordDto updatePasswordDto) {
        if (updatePasswordDto == null){
            throw new CustomException(400,"参数错误");
        }

        UserWithChat userWithChat = userWithChatMapper.selectById(updatePasswordDto.getObjectId());
        if (userWithChat.getPassword().equals(MD5Utils.stringMD5(updatePasswordDto.getOldPassword()))){
            String s = MD5Utils.stringMD5(updatePasswordDto.getPassword());
            userWithChat.setDef(false);
            userWithChat.setPassword(s);
            int update = userWithChatMapper.updateById(userWithChat);
            if (update > 0){
                return CommonResponse.success();
            }else {
                return CommonResponse.error(ErrorCode.UPDATE_FAILED.getCode(),ErrorCode.UPDATE_FAILED.getMessage(),ErrorCode.UPDATE_FAILED.getMessage());
            }
        }else {
            return CommonResponse.error(ErrorCode.OLD_PASSWORD_FAILED.getCode(), ErrorCode.OLD_PASSWORD_FAILED.getMessage(), ErrorCode.OLD_PASSWORD_FAILED.getMessage());
        }

    }

    @Override
    public FindPasswordResponse findPassword(FindPasswordDto findPasswordDto) {
        if (findPasswordDto == null){
            throw new CustomException(400,"参数错误");
        }
        UserWithChat userWithChat = userWithChatMapper.selectOne(new QueryWrapper<UserWithChat>().eq("name", findPasswordDto.getName()).eq("email", findPasswordDto.getEmail()));
        if (userWithChat == null){
            return FindPasswordResponse.error(ErrorCode.NOT_EXIST.getCode());
        }
        return FindPasswordResponse.success(userWithChat);
    }

    @Override
    public CommonResponse changePassword(UpdatePasswordDto updatePasswordDto) {
        if (updatePasswordDto == null){
            throw new CustomException(400,"参数错误");
        }

        UserWithChat userWithChat = userWithChatMapper.selectById(updatePasswordDto.getObjectId());
        userWithChat.setPassword(MD5Utils.stringMD5(updatePasswordDto.getPassword()));
        userWithChat.setDef(false);
        int update = userWithChatMapper.updateById(userWithChat);
        if (update > 0){
            return CommonResponse.success();
        }else {
            return CommonResponse.error(ErrorCode.UPDATE_FAILED.getCode(),ErrorCode.UPDATE_FAILED.getMessage(),ErrorCode.UPDATE_FAILED.getMessage());
        }
    }

    @Override
    public CommonResponse getUserWithChatByName(UserWithChat userWithChat) {
        if (userWithChat == null){
            throw new CustomException(400,"参数错误");
        }

        UserWithChat name = userWithChatMapper.selectOne(new QueryWrapper<UserWithChat>().eq("name", userWithChat.getName()));
        if (name == null){
            return CommonResponse.error(ErrorCode.NOT_FOUND.getCode(), ErrorCode.NOT_FOUND.getMessage(), ErrorCode.NOT_FOUND.getMessage());
        }
        return CommonResponse.success();
    }


}
